package cn.xiaoyu.su.interceptor;

import cn.xiaoyu.su.enums.BizCodeEnum;
import cn.xiaoyu.su.model.LoginUser;
import cn.xiaoyu.su.util.CommonUtil;
import cn.xiaoyu.su.util.JWTUtil;
import cn.xiaoyu.su.util.JsonData;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author sufs
 * @date 2022/10/31 13:10
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    public static  ThreadLocal<LoginUser> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (HttpMethod.OPTIONS.toString().equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpStatus.NO_CONTENT.value());
            return true;
        }

        String accessToken = StringUtils.isBlank(request.getHeader("token")) ? request.getParameter("token") : request.getHeader("token");

        if (StringUtils.isBlank(accessToken)) {
            CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
            log.error("登录token为空");
            return false;
        }

        Claims claims = JWTUtil.checkJWT(accessToken);

        if (claims == null) {
            CommonUtil.sendJsonMessage(response,JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
            return false;
        }

        LoginUser loginUser = LoginUser.builder()
                .accountNo(claims.get("account_no", Long.class))
                .headImg(claims.get("head_img", String.class))
                .username(claims.get("username", String.class))
                .auth(claims.get("auth", String.class))
                .phone(claims.get("phone", String.class))
                .mail(claims.get("mail", String.class))
                .build();

        threadLocal.set(loginUser);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        threadLocal.remove();
    }
}
